<?php
namespace app\admin\controller;

use app\admin\module\RoleModule;
use app\BaseController;
use app\common\validate\Role as RoleValidate;
use app\Request;
use think\Exception;

class Role extends BaseController{

    public function index(Request $request){
        $data = RoleModule::page($request->param("pageSize",10));
        return $this->success("获取成功",$data);
    }

    public function create(Request $request){
        $data = $request->post();
        $validate = new RoleValidate();
        if(!$validate->check($data)){
            throw new Exception($validate->getError());
        }
        RoleModule::create($data);
        return $this->success("添加成功");
    }

    public function update(Request $request){
        $data = $request->post();
        $validate = new RoleValidate();
        if(!$validate->check($data)){
            throw new Exception($validate->getError());
        }
        RoleModule::update($data);
        return $this->success("更新成功");
    }

    public function remove(Request $request){
        RoleModule::del($request->param('id'));
        return $this->success("删除成功");
    }

    public function permission(Request $request){
        $id = $request->param('id');
        return $this->success('获取成功',RoleModule::permission($id));
    }

    public function savePermission(Request $request){
        $post = $request->post();
        if(empty($post['id'])){
            throw new Exception("请选择角色");
        }
        if(empty($post['permission'])){
            $post['permission'] = [];
        }
        RoleModule::savePermission($post['id'],$post['permission']);
        return $this->success("保存成功");
    }
}